<template>
  <div class="registration-list">
    <div class="page-title">挂号管理</div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card stat-card-today">
          <div class="stat-content">
            <div class="stat-label">今日挂号</div>
            <div class="stat-value">{{ stats.todayRegistration }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card stat-card-completed">
          <div class="stat-content">
            <div class="stat-label">已就诊</div>
            <div class="stat-value">{{ stats.completed }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card stat-card-pending">
          <div class="stat-content">
            <div class="stat-label">待就诊</div>
            <div class="stat-value">{{ stats.pending }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card stat-card-processing">
          <div class="stat-content">
            <div class="stat-label">就诊中</div>
            <div class="stat-value">{{ stats.processing }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选栏 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select v-model="status" placeholder="就诊状态" @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="未就诊" value="1" />
            <el-option label="已就诊" value="3" />
            <el-option label="就诊中" value="4" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="deptName" placeholder="科室" @change="handleSearch" :loading="!departmentList.length">
            <el-option label="全部" value="" />
            <el-option-group
                v-for="dept in departmentList"
                :key="dept.dept_id"
                :label="dept.name"
            >
              <el-option
                  :label="dept.name"
                  :value="dept.name"
                  :key="`parent-${dept.dept_id}`"
              />
              <el-option
                  v-for="childDept in dept.children"
                  :key="childDept.dept_id"
                  :label="childDept.name"
                  :value="childDept.name"
              />
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchKey" placeholder="搜索患者姓名/挂号单号" @keyup.enter="handleSearch" />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button @click="resetFilter">重置</el-button>
        </el-col>
      </el-row>

      <!-- 显示当前筛选条件 -->
      <div v-if="hasActiveFilters" class="filter-info">
        <el-tag
            v-if="status"
            closable
            @close="clearStatus"
            type="info"
            style="margin-right: 8px;"
        >
          状态: {{ getStatusText(parseInt(status)) }}
        </el-tag>
        <el-tag
            v-if="deptName"
            closable
            @close="clearDeptName"
            type="info"
            style="margin-right: 8px;"
        >
          科室: {{ deptName }}
        </el-tag>
        <el-tag
            v-if="searchKey"
            closable
            @close="clearSearchKey"
            type="info"
            style="margin-right: 8px;"
        >
          搜索: {{ searchKey }}
        </el-tag>
      </div>
    </el-card>

    <!-- 挂号列表 -->
    <el-card class="patient-list-card">
      <el-table
          :data="patientList"
          border
          style="width: 100%"
          @row-click="handlePatientClick"
          v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="order_id" label="序号" width="80" />
        <el-table-column prop="patient_name" label="患者姓名" />
        <el-table-column prop="gender_text" label="性别" width="80" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="order_no" label="挂号单号" />
        <el-table-column prop="dept_name" label="科室" />
        <el-table-column prop="visit_no" label="就诊号" />
        <el-table-column prop="create_time" label="挂号时间">
          <template #default="scope">
            {{ formatDateTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="order_status" label="状态">
          <template #default="scope">
            <el-tag
                :type="getStatusType(scope.row.order_status)"
            >
              {{ getStatusText(scope.row.order_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleStartConsultation(scope.row)"
                :disabled="scope.row.order_status !== 1"
            >
              开始就诊
            </el-button>
            <el-button
                size="small"
                type="success"
                @click="handleCompleteConsultation(scope.row)"
                :disabled="scope.row.order_status !== 4"
            >
              完成就诊
            </el-button>
            <el-button
                size="small"
                type="text"
                @click="handleViewDetails(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        />
      </div>
    </el-card>

    <!-- 患者详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="患者就诊详情"
        :width="1000"
        :before-close="handleDialogClose"
    >
      <el-row :gutter="20">
        <!-- 患者基本信息 -->
        <el-col :span="24">
          <el-card class="patient-basic-card">
            <div class="patient-avatar-container">
              <div class="patient-avatar">
                <el-avatar :size="60">
                  <User />
                </el-avatar>
                <div class="patient-tag" v-if="currentPatient.order_status === 4">
                  <el-tag type="warning">就诊中</el-tag>
                </div>
              </div>

              <div class="patient-main-info">
                <div class="name-and-id">
                  <h3 class="patient-name">{{ currentPatient.patientName || currentPatient.name || '-' }}</h3>
                  <span class="patient-id">ID: {{ currentPatient.patient_id || currentPatient.patientId || '-' }}</span>
                </div>

                <div class="patient-basic-details">
                  <div class="detail-item">
                    <span class="detail-label">性别：</span>
                    <span class="detail-value">
                      {{
                        currentPatient.gender === 1 ? '男' :
                            currentPatient.gender === 2 ? '女' :
                                currentPatient.gender_text || '-'
                      }}
                    </span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">年龄：</span>
                    <span class="detail-value">{{ currentPatient.age ? currentPatient.age + '岁' : '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">出生日期：</span>
                    <span class="detail-value">{{ currentPatient.birth_date || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">联系电话：</span>
                    <span class="detail-value">{{ currentPatient.phone || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">身份证号：</span>
                    <span class="detail-value">{{ maskIdCard(currentPatient.id_card) || '-' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细内容标签页 -->
      <el-tabs type="card" class="detail-tabs" v-model="activeTab">
        <!-- 就诊基本信息 -->
        <el-tab-pane label="就诊信息" name="visit-info">
          <el-card>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="visit-info-item">
                  <span class="info-label">挂号单号：</span>
                  <span class="info-value">{{ currentPatient.registrationNo || currentPatient.order_no || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊科室：</span>
                  <span class="info-value">{{ currentPatient.dept_name || currentPatient.department || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">接诊医生：</span>
                  <span class="info-value">{{ currentPatient.doctor_name || currentPatient.doctorName || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊时间：</span>
                  <span class="info-value">{{ currentPatient.visitTime || formatDateTime(currentPatient.visit_time) || formatDateTime(currentPatient.create_time) || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊状态：</span>
                  <span class="info-value">
                    <el-tag
                        :type="
                        currentPatient.order_status === 1 ? 'info' :
                        currentPatient.order_status === 4 ? 'warning' :
                        currentPatient.order_status === 3 ? 'success' : 'info'
                      "
                    >
                      {{
                        currentPatient.order_status === 1 ? '待就诊' :
                            currentPatient.order_status === 4 ? '就诊中' :
                                currentPatient.order_status === 3 ? '已完成' : '待就诊'
                      }}
                    </el-tag>
                  </span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">症状描述：</span>
                  <span class="info-value">{{ currentPatient.symptoms || currentPatient.symptoms || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊号：</span>
                  <span class="info-value">{{ currentPatient.visit_no || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊费用：</span>
                  <span class="info-value">{{ currentPatient.amount ? '¥' + currentPatient.amount : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">关系：</span>
                  <span class="info-value">{{ currentPatient.relationship || '-' }}</span>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="visit-info-item">
                  <span class="info-label">支付状态：</span>
                  <span class="info-value">
                    <el-tag :type="currentPatient.pay_status === 1 ? 'success' : 'warning'">
                      {{ currentPatient.pay_status === 1 ? '已支付' : '未支付' }}
                    </el-tag>
                  </span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">支付时间：</span>
                  <span class="info-value">{{ currentPatient.pay_time ? formatDateTime(currentPatient.pay_time) : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">取消时间：</span>
                  <span class="info-value">{{ currentPatient.cancel_time ? formatDateTime(currentPatient.cancel_time) : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">创建时间：</span>
                  <span class="info-value">{{ currentPatient.create_time ? formatDateTime(currentPatient.create_time) : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">更新时间：</span>
                  <span class="info-value">{{ currentPatient.update_time ? formatDateTime(currentPatient.update_time) : '-' }}</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <el-card class="mt-4">
            <template #header>
              <span>病情诊断</span>
              <el-button
                  size="small"
                  type="text"
                  @click="handleEditDiagnosis"
                  v-if="currentPatient.order_status !== 3"
              >
                编辑
              </el-button>
            </template>

            <!-- 病情诊断显示 -->
            <div v-if="!editDiagnosis" class="diagnosis-display">
              <div class="diagnosis-item">
                <span class="diagnosis-label">主诉：</span>
                <div class="diagnosis-content">{{ currentPatient.medicalRecord?.chief_complaint || '暂无主诉' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">现病史：</span>
                <div class="diagnosis-content">{{ currentPatient.medicalRecord?.present_illness || '暂无现病史' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">体格检查：</span>
                <div class="diagnosis-content">{{ currentPatient.medicalRecord?.physical_exam || '暂无体格检查结果' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">辅助检查：</span>
                <div class="diagnosis-content">{{ currentPatient.medicalRecord?.auxiliary_exam || '暂无辅助检查结果' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">诊断结果：</span>
                <div class="diagnosis-content">{{ currentPatient.medicalRecord?.diagnosis || '暂无诊断结果' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">治疗方案：</span>
                <div class="diagnosis-content">{{ currentPatient.medicalRecord?.treatment_plan || '暂无治疗方案' }}</div>
              </div>
            </div>

            <!-- 病情诊断编辑表单 -->
            <el-form v-if="editDiagnosis && diagnosisForm" ref="diagnosisFormRef" :model="diagnosisForm" label-width="100px">
              <el-form-item label="主诉：">
                <el-input
                    v-model="diagnosisForm.chiefComplaint"
                    type="textarea"
                    rows="2"
                    placeholder="请输入患者主诉..."
                />
              </el-form-item>
              <el-form-item label="现病史：">
                <el-input
                    v-model="diagnosisForm.presentIllness"
                    type="textarea"
                    rows="3"
                    placeholder="请输入现病史..."
                />
              </el-form-item>
              <el-form-item label="体格检查：">
                <el-input
                    v-model="diagnosisForm.physicalExam"
                    type="textarea"
                    rows="3"
                    placeholder="请输入体格检查结果..."
                />
              </el-form-item>
              <el-form-item label="辅助检查：">
                <el-input
                    v-model="diagnosisForm.auxiliaryExam"
                    type="textarea"
                    rows="3"
                    placeholder="请输入辅助检查结果..."
                />
              </el-form-item>
              <el-form-item label="诊断结果：">
                <el-input
                    v-model="diagnosisForm.diagnosis"
                    type="textarea"
                    rows="2"
                    placeholder="请输入诊断结果..."
                />
              </el-form-item>
              <el-form-item label="治疗方案：">
                <el-input
                    v-model="diagnosisForm.treatmentPlan"
                    type="textarea"
                    rows="3"
                    placeholder="请输入治疗方案..."
                />
              </el-form-item>

              <div class="form-actions">
                <el-button @click="editDiagnosis = false">取消</el-button>
                <el-button type="primary" @click="saveDiagnosis">保存</el-button>
              </div>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
            type="primary"
            @click="handleStartConsultation(currentPatient)"
            v-if="currentPatient.order_status === 1"
        >
          开始就诊
        </el-button>
        <el-button
            type="success"
            @click="handleCompleteConsultation(currentPatient)"
            v-if="currentPatient.order_status === 4"
        >
          完成就诊
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { User } from '@element-plus/icons-vue';
import axiosInstance from '../axios/axiosInstance.js';
import { ElMessage } from 'element-plus';



// 计算属性
const hasActiveFilters = computed(() => {
  return status.value || deptName.value || searchKey.value;
});

// 获取所有科室的扁平化列表（用于调试）
const allDepartments = computed(() => {
  const departments = [];
  departmentList.value.forEach(dept => {
    departments.push(dept.name);
    if (dept.children) {
      dept.children.forEach(child => {
        departments.push(child.name);
      });
    }
  });
  return departments;
});

// 状态管理
const status = ref('');
const deptName = ref('');
const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 患者列表数据
const patientList = ref([]);

// 科室数据
const departmentList = ref([]);

// 统计数据
const stats = ref({
  todayRegistration: 0,
  completed: 0,
  pending: 0,
  processing: 0
});

// 对话框状态
const detailDialogVisible = ref(false);
const currentPatient = ref({});
const activeTab = ref('visit-info');
const editDiagnosis = ref(false);
const diagnosisFormRef = ref(null);

// 表单数据
const diagnosisForm = ref({
  chiefComplaint: '',
  presentIllness: '',
  physicalExam: '',
  auxiliaryExam: '',
  diagnosis: '',
  treatmentPlan: ''
});

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const response = await axiosInstance.get('/api/v1/departments');
    console.log('科室数据:', response.data);

    if (response.data && response.data.data) {
      departmentList.value = response.data.data;
      console.log('加载的科室列表:', allDepartments.value);
    } else {
      departmentList.value = [];
      console.log('未获取到科室数据');
    }
  } catch (error) {
    console.error('获取科室列表失败:', error);
    departmentList.value = [];
  }
};

// 获取挂号列表
// 注意：后端应该过滤掉待支付(0)和已取消(2)的订单，只返回有效的就诊订单
const fetchRegistrationList = async () => {
  loading.value = true;
  try {
    const params = {
      status: status.value || undefined,
      deptName: deptName.value || undefined,
      searchKey: searchKey.value || undefined,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    console.log('发送查询参数:', params);

    const response = await axiosInstance.get('/api/v1/registrationList', { params });

    console.log('后端返回数据:', response.data);

    if (response.data && response.data.list) {
      // 直接使用后端返回的数据，不再进行前端过滤
      // 注意：后端应该已经过滤掉了待支付(0)和已取消(2)的订单
      patientList.value = response.data.list;
      total.value = response.data.total || response.data.list.length;

      // 获取患者详细信息
      await fetchPatientDetails();

      // 计算统计数据
      calculateStats();
    } else {
      patientList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取挂号列表失败:', error);
    ElMessage.error('获取挂号列表失败');
    patientList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取患者详细信息
const fetchPatientDetails = async () => {
  const promises = patientList.value.map(async (order) => {
    if (order.patient_id) {
      try {
        const response = await axiosInstance.get(`/api/v1/patient/${order.patient_id}`);
        if (response.data && response.data.data) {
          const patientData = response.data.data;
          // 计算年龄
          const birthDate = new Date(patientData.birth_date);
          const today = new Date();
          const age = today.getFullYear() - birthDate.getFullYear();
          const monthDiff = today.getMonth() - birthDate.getMonth();
          const actualAge = monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate()) ? age - 1 : age;

          // 更新患者信息
          order.age = actualAge;
          order.gender_text = patientData.gender === 1 ? '男' : patientData.gender === 2 ? '女' : '未知';
        }
      } catch (error) {
        console.error(`获取患者${order.patient_id}信息失败:`, error);
        order.age = '未知';
        order.gender_text = '未知';
      }
    } else {
      // 如果没有patient_id，设置默认值
      order.age = '未知';
      order.gender_text = '未知';
    }
  });

  await Promise.all(promises);
};

// 计算统计数据
const calculateStats = () => {
  const today = new Date().toISOString().split('T')[0];

  stats.value = {
    todayRegistration: patientList.value.filter(item =>
        item.create_time && item.create_time.includes(today)
    ).length,
    completed: patientList.value.filter(item => item.order_status === 3).length,
    pending: patientList.value.filter(item => item.order_status === 1).length,
    processing: patientList.value.filter(item => item.order_status === 4).length
  };
};

// 获取状态类型
const getStatusType = (orderStatus) => {
  switch (orderStatus) {
    case 1: return 'warning'; // 未就诊 - 黄色
    case 3: return 'success'; // 已就诊 - 绿色
    case 4: return 'primary'; // 就诊中 - 蓝色
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (orderStatus) => {
  switch (orderStatus) {
    case 1: return '未就诊';
    case 3: return '已就诊';
    case 4: return '就诊中';
    default: return '未知';
  }
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  try {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return dateTimeStr;
  }
};

// 转换患者数据格式为doctor.vue期望的格式
const convertPatientData = (row) => {
  return {
    id: row.order_id,
    patientName: row.patient_name,
    gender: row.gender_text,
    age: row.age,
    registrationNo: row.order_no,
    registrationTime: formatDateTime(row.create_time),
    symptoms: row.symptoms,
    status: getStatusText(row.order_status),
    order_status: row.order_status,
    visit_no: row.visit_no,
    dept_name: row.dept_name,
    visit_time: row.visit_time,
    update_time: row.update_time,
    order_id: row.order_id,
    patient_id: row.patient_id,
    doctor_id: row.doctor_id,
    doctor_name: row.doctor_name,
    amount: row.amount,
    // 添加更多字段以确保完整显示
    pay_status: row.pay_status,
    pay_time: row.pay_time,
    cancel_time: row.cancel_time,
    create_time: row.create_time,
    department: row.dept_name,
    visitTime: formatDateTime(row.visit_time || row.create_time)
  };
};

// 方法
const handleSearch = () => {
  console.log('执行搜索，参数:', {
    status: status.value,
    deptName: deptName.value,
    searchKey: searchKey.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
  currentPage.value = 1;
  fetchRegistrationList();
};

const resetFilter = () => {
  console.log('重置筛选条件');
  status.value = '';
  deptName.value = '';
  searchKey.value = '';
  currentPage.value = 1;
  fetchRegistrationList();
};

// 清除单个筛选条件
const clearStatus = () => {
  status.value = '';
  handleSearch();
};

const clearDeptName = () => {
  deptName.value = '';
  handleSearch();
};

const clearSearchKey = () => {
  searchKey.value = '';
  handleSearch();
};

const handleSizeChange = (val) => {
  console.log('改变每页显示数量:', val);
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  fetchRegistrationList();
};

const handleCurrentChange = (val) => {
  console.log('改变当前页:', val);
  currentPage.value = val;
  fetchRegistrationList();
};

const handlePatientClick = (row) => {
  handleViewDetails(row);
};

// 关闭对话框
const handleDialogClose = () => {
  detailDialogVisible.value = false;
  currentPatient.value = {};
  editDiagnosis.value = false;
  // 重置表单数据
  diagnosisForm.value = {
    chiefComplaint: '',
    presentIllness: '',
    physicalExam: '',
    auxiliaryExam: '',
    diagnosis: '',
    treatmentPlan: ''
  };
};

// 编辑病情诊断
const handleEditDiagnosis = () => {
  // 从后端数据填充表单
  if (currentPatient.value.medicalRecord) {
    diagnosisForm.value.chiefComplaint = currentPatient.value.medicalRecord.chief_complaint || '';
    diagnosisForm.value.presentIllness = currentPatient.value.medicalRecord.present_illness || '';
    diagnosisForm.value.physicalExam = currentPatient.value.medicalRecord.physical_exam || '';
    diagnosisForm.value.auxiliaryExam = currentPatient.value.medicalRecord.auxiliary_exam || '';
    diagnosisForm.value.diagnosis = currentPatient.value.medicalRecord.diagnosis || '';
    diagnosisForm.value.treatmentPlan = currentPatient.value.medicalRecord.treatment_plan || '';
  }
  editDiagnosis.value = true;
};

// 保存诊断信息
const saveDiagnosis = async () => {
  try {
    // 检查是否有record_id，如果没有则创建新记录
    let recordId = currentPatient.value.medicalRecord?.record_id;

    const consultationData = {
      patient_id: currentPatient.value.patient_id,
      doctor_id: currentPatient.value.doctor_id || 1,
      order_id: currentPatient.value.order_id,
      visit_date: new Date().toISOString().split('T')[0],
      chief_complaint: diagnosisForm.value.chiefComplaint || '',
      present_illness: diagnosisForm.value.presentIllness || '',
      physical_exam: diagnosisForm.value.physicalExam || '',
      auxiliary_exam: diagnosisForm.value.auxiliaryExam || '',
      diagnosis: diagnosisForm.value.diagnosis || '',
      treatment_plan: diagnosisForm.value.treatmentPlan || '',
      prescription: currentPatient.value.medicalRecord?.prescription || '',
      advice: currentPatient.value.medicalRecord?.advice || '',
      next_visit_date: currentPatient.value.medicalRecord?.next_visit_date || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      status: 1
    };

    // 如果有record_id，添加到请求数据中
    if (recordId) {
      consultationData.record_id = recordId;
    }

    const response = await axiosInstance.post('/api/v1/update', consultationData);

    console.log('保存诊断响应:', response.data);
    console.log('响应数据类型:', typeof response.data);
    console.log('响应数据键:', Object.keys(response.data || {}));

    // 检查响应是否成功 - 后端可能直接返回数据对象或包含code字段的响应
    const isSuccess = response.data && (
        response.data.code === '0' ||
        response.data.code === 0 ||
        response.data.record_id ||
        response.data.patient_id ||
        response.data.success === true
    );

    console.log('判断是否成功:', isSuccess);

    if (isSuccess) {
      ElMessage.success('诊断信息保存成功');

      // 更新本地数据
      if (currentPatient.value.medicalRecord) {
        // 如果后端直接返回了更新后的数据，使用后端返回的数据
        if (response.data.record_id) {
          currentPatient.value.medicalRecord.chief_complaint = response.data.chief_complaint || '';
          currentPatient.value.medicalRecord.present_illness = response.data.present_illness || '';
          currentPatient.value.medicalRecord.physical_exam = response.data.physical_exam || '';
          currentPatient.value.medicalRecord.auxiliary_exam = response.data.auxiliary_exam || '';
          currentPatient.value.medicalRecord.diagnosis = response.data.diagnosis || '';
          currentPatient.value.medicalRecord.treatment_plan = response.data.treatment_plan || '';
          currentPatient.value.medicalRecord.record_id = response.data.record_id;
        } else {
          // 使用表单数据更新
          currentPatient.value.medicalRecord.chief_complaint = diagnosisForm.value.chiefComplaint || '';
          currentPatient.value.medicalRecord.present_illness = diagnosisForm.value.presentIllness || '';
          currentPatient.value.medicalRecord.physical_exam = diagnosisForm.value.physicalExam || '';
          currentPatient.value.medicalRecord.auxiliary_exam = diagnosisForm.value.auxiliaryExam || '';
          currentPatient.value.medicalRecord.diagnosis = diagnosisForm.value.diagnosis || '';
          currentPatient.value.medicalRecord.treatment_plan = diagnosisForm.value.treatmentPlan || '';

          // 如果返回了新的record_id，更新它
          if (response.data.data && response.data.data.record_id) {
            currentPatient.value.medicalRecord.record_id = response.data.data.record_id;
          }
        }
      }

      // 更新列表中的数据
      const index = patientList.value.findIndex(item => item.id === currentPatient.value.id);
      if (index !== -1) {
        // 只更新诊断相关的字段，保持原有的order_status
        patientList.value[index].medicalRecord = { ...currentPatient.value.medicalRecord };
      }

      editDiagnosis.value = false;
    } else {
      ElMessage.error('保存诊断信息失败');
    }
  } catch (error) {
    console.error('保存诊断信息失败:', error);
    ElMessage.error('保存诊断信息失败');
  }
};

// 格式化科室名称
const formatDepartment = (deptCode) => {
  const deptMap = {
    'internal': '内科',
    'surgery': '外科',
    'pediatrics': '儿科',
    'obstetrics': '妇产科',
    'dermatology': '皮肤科'
  };
  return deptMap[deptCode] || deptCode;
};

// 身份证号掩码处理
const maskIdCard = (idCard) => {
  if (!idCard || idCard.length !== 18) return idCard;
  return idCard.replace(/^(\d{6})\d{8}(\d{4})$/, '$1********$2');
};

// 显示患者详情对话框
const handleViewDetails = async (row) => {
  try {
    // 获取患者基本信息
    const patientData = convertPatientData(row);

    // 获取患者详细信息
    let patientDetails = {};
    try {
      const patientResponse = await axiosInstance.get(`/api/v1/patient/${row.patient_id}`);
      if (patientResponse.data && patientResponse.data.data) {
        patientDetails = patientResponse.data.data;
      }
    } catch (error) {
      console.error(`获取患者${row.patient_id}详情失败:`, error);
    }

    // 获取就诊记录详情
    const recordResponse = await axiosInstance.get('/api/v1/get-by-order', {
      params: { orderId: row.order_id }
    });

    if (recordResponse.data && recordResponse.data.data) {
      // 合并患者基本信息、详细信息和就诊记录
      const fullPatientData = {
        ...patientData,
        ...patientDetails, // 添加患者详细信息（出生日期、联系电话、身份证号等）
        medicalRecord: recordResponse.data.data
      };

      currentPatient.value = fullPatientData;

      // 初始化诊断表单数据
      diagnosisForm.value = {
        chiefComplaint: recordResponse.data.data.chief_complaint || '',
        presentIllness: recordResponse.data.data.present_illness || '',
        physicalExam: recordResponse.data.data.physical_exam || '',
        auxiliaryExam: recordResponse.data.data.auxiliary_exam || '',
        diagnosis: recordResponse.data.data.diagnosis || '',
        treatmentPlan: recordResponse.data.data.treatment_plan || ''
      };
    } else {
      // 如果没有就诊记录，只显示基本信息
      currentPatient.value = {
        ...patientData,
        ...patientDetails // 添加患者详细信息
      };

      // 重置诊断表单数据
      diagnosisForm.value = {
        chiefComplaint: '',
        presentIllness: '',
        physicalExam: '',
        auxiliaryExam: '',
        diagnosis: '',
        treatmentPlan: ''
      };
    }

    detailDialogVisible.value = true;
  } catch (error) {
    console.error('获取就诊记录失败:', error);
    // 即使获取就诊记录失败，也要显示基本信息
    const patientData = convertPatientData(row);
    currentPatient.value = patientData;
    detailDialogVisible.value = true;
  }
};

// 开始就诊（更新状态）
const handleStartConsultation = async (row) => {
  try {
    // 构建API路径和参数
    const apiUrl = `/api/v1/${row.order_id}/status`;
    const params = { status: 4 };

    // 调用后端API更新订单状态为4（就诊中）
    const response = await axiosInstance.put(apiUrl, null, { params });

    if (response.data) {
      // 使用后端返回的更新后数据更新本地状态
      const index = patientList.value.findIndex(item => item.order_id === row.order_id);
      if (index !== -1) {
        // 合并后端返回的数据到本地数据
        Object.assign(patientList.value[index], response.data);
      }

      ElMessage.success('开始就诊成功');
      // 更新对话框中的数据
      if (currentPatient.value.order_id === row.order_id) {
        currentPatient.value = convertPatientData(patientList.value[index]);
      }
    } else {
      ElMessage.error('更新失败：未收到有效响应');
    }
  } catch (error) {
    console.error('开始就诊失败:', error);

    if (error.response) {
      ElMessage.error(`开始就诊失败：${error.response.data?.message || '服务器错误'} (${error.response.status})`);
    } else if (error.request) {
      ElMessage.error('开始就诊失败：网络连接错误');
    } else {
      ElMessage.error(`开始就诊失败：${error.message}`);
    }
  }
};

// 完成就诊（更新状态为3）
const handleCompleteConsultation = async (row) => {
  try {
    // 构建API路径和参数
    const apiUrl = `/api/v1/${row.order_id}/status`;
    const params = { status: 3 };

    // 调用后端API更新订单状态为3（已就诊）
    const response = await axiosInstance.put(apiUrl, null, { params });

    if (response.data) {
      // 使用后端返回的更新后数据更新本地状态
      const index = patientList.value.findIndex(item => item.order_id === row.order_id);
      if (index !== -1) {
        // 合并后端返回的数据到本地数据
        Object.assign(patientList.value[index], response.data);
      }

      ElMessage.success('完成就诊成功');
      // 更新对话框中的数据
      if (currentPatient.value.order_id === row.order_id) {
        currentPatient.value = convertPatientData(patientList.value[index]);
      }
    } else {
      ElMessage.error('更新失败：未收到有效响应');
    }
  } catch (error) {
    console.error('完成就诊失败:', error);
    console.error('错误详情:', {
      message: error.message,
      config: error.config,
      response: error.response,
      request: error.request
    });

    if (error.response) {
      ElMessage.error(`完成就诊失败：${error.response.data?.message || '服务器错误'} (${error.response.status})`);
    } else if (error.request) {
      ElMessage.error('完成就诊失败：网络连接错误');
    } else {
      ElMessage.error(`完成就诊失败：${error.message}`);
    }
  }
};

// 页面加载时获取数据
onMounted(async () => {
  // 先获取科室数据，再获取挂号列表
  await fetchDepartments();
  await fetchRegistrationList();
});
</script>

<style scoped>
.registration-list {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

/* 今日挂号卡片 */
.stat-card-today {
  border-left: 4px solid #409eff;
}

.stat-card-today .stat-value {
  color: #409eff;
}

/* 已就诊卡片 */
.stat-card-completed {
  border-left: 4px solid #67c23a;
}

.stat-card-completed .stat-value {
  color: #67c23a;
}

/* 待就诊卡片 */
.stat-card-pending {
  border-left: 4px solid #e6a23c;
}

.stat-card-pending .stat-value {
  color: #e6a23c;
}

/* 就诊中卡片 */
.stat-card-processing {
  border-left: 4px solid #409eff;
}

.stat-card-processing .stat-value {
  color: #409eff;
}

.stat-content {
  text-align: center;
  padding: 10px;
}

.stat-label {
  font-size: 14px;
  margin-bottom: 8px;
  color: #606266;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.filter-info {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.patient-list-card {
  padding: 0;
}

.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 0 15px 15px;
}

/* 患者详情对话框样式 */
.patient-basic-card {
  margin-bottom: 20px;
}

.patient-avatar-container {
  display: flex;
  align-items: flex-start;
}

.patient-avatar {
  position: relative;
  margin-right: 20px;
}

.patient-tag {
  position: absolute;
  top: -5px;
  right: -5px;
}

.patient-main-info {
  flex: 1;
}

.name-and-id {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.patient-name {
  font-size: 18px;
  font-weight: 600;
  margin-right: 15px;
}

.patient-id {
  color: #64748b;
  font-size: 14px;
}

.patient-basic-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 30px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  color: #64748b;
  width: 90px;
}

.detail-value {
  flex-grow: 1;
  font-weight: 500;
}

.detail-tabs {
  margin-top: 20px;
}

.mt-4 {
  margin-top: 16px !important;
}

/* 就诊信息样式 */
.visit-info-item {
  margin-bottom: 12px;
}

.info-label {
  color: #64748b;
  display: inline-block;
  width: 100px;
}

.info-value {
  font-weight: 500;
}

/* 病情诊断显示样式 */
.diagnosis-display {
  padding: 15px;
  background-color: #f8fafc;
  border-radius: 4px;
  border: 1px solid #e2e8f0;
}

/* 表单操作按钮样式 */
.form-actions {
  margin-top: 15px;
  text-align: right;
}

.diagnosis-item {
  margin-bottom: 15px;
}

.diagnosis-item:last-child {
  margin-bottom: 0;
}

.diagnosis-label {
  display: block;
  font-weight: 600;
  color: #374151;
  margin-bottom: 5px;
  font-size: 14px;
}

.diagnosis-content {
  padding: 10px;
  background-color: #ffffff;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  min-height: 20px;
  line-height: 1.5;
  color: #1f2937;
  white-space: pre-line;
}
</style>